package com.xzzz.irda.guardcat.core.metric.druid;


import cn.hutool.core.collection.CollectionUtil;
import com.xzzz.common.base.util.JmxUtil;

import javax.management.ObjectName;
import java.util.Optional;
import java.util.Set;

/**
 * druid 信息
 *
 * @author xzzz
 * @since 1.0.0
 */
public class DruidInfo {

    /**
     * 获取 Druid 连接池信息
     *
     * @return Set<ObjectName>
     */
    public static DruidConnectionPoolInfo getDruidConnectionPoolInfo() {
        Set<ObjectName> connPools = JmxUtil.getObjectNameSet(JmxUtil.DRUID_DATA_SOURCE);
        if (CollectionUtil.isEmpty(connPools)) {
            return null;
        }
        Optional<ObjectName> connPoolOptional = connPools.stream().findFirst();
        if (!connPoolOptional.isPresent()) {
            return null;
        }
        ObjectName connPool = connPoolOptional.get();
        DruidConnectionPoolInfo druidConnectionPoolInfo = new DruidConnectionPoolInfo();
        druidConnectionPoolInfo.setCreatedTime(JmxUtil.getMbeanDateVal(connPool, "CreatedTime"));
        druidConnectionPoolInfo.setName(JmxUtil.getMbeanStrVal(connPool, "Name"));
        druidConnectionPoolInfo.setUrl(JmxUtil.getMbeanStrVal(connPool, "Url"));
        druidConnectionPoolInfo.setUsername(JmxUtil.getMbeanStrVal(connPool, "Username"));
        druidConnectionPoolInfo.setVersion(JmxUtil.getMbeanStrVal(connPool, "Version"));
        druidConnectionPoolInfo.setMinIdle(JmxUtil.getMbeanIntegerVal(connPool, "MinIdle"));
        druidConnectionPoolInfo.setMaxIdle(JmxUtil.getMbeanIntegerVal(connPool, "MaxIdle"));
        druidConnectionPoolInfo.setMaxActive(JmxUtil.getMbeanIntegerVal(connPool, "MaxActive"));
        druidConnectionPoolInfo.setActiveCount(JmxUtil.getMbeanIntegerVal(connPool, "ActiveCount"));
        druidConnectionPoolInfo.setPoolingCount(JmxUtil.getMbeanIntegerVal(connPool, "PoolingCount"));
        druidConnectionPoolInfo.setMaxWait(JmxUtil.getMbeanLongVal(connPool, "MaxWait"));
        druidConnectionPoolInfo.setWaitThreadCount(JmxUtil.getMbeanIntegerVal(connPool, "NotEmptyWaitThreadCount"));
        druidConnectionPoolInfo.setMaxWaitThreadCount(JmxUtil.getMbeanIntegerVal(connPool, "MaxWaitThreadCount"));
        druidConnectionPoolInfo.setResetCount(JmxUtil.getMbeanLongVal(connPool, "ResetCount"));
        return druidConnectionPoolInfo;
    }
}
